<template>
    <view class="container">
        <!-- 消息列表 -->
        <scroll-view class="message-list" scroll-y :scroll-top="scrollTop" scroll-with-animation="true">
            <view class="message-container" v-for="(item, index) in messages" :key="index">
                <view class="message" :class="{ 'user-message': item.isUser, 'ai-message': !item.isUser }">
                    {{ item.isUser ? item.content : item.displayContent }}
                </view>
            </view>
            <view v-if="isTyping" class="typing-indicator">
                <view class="dot"></view>
                <view class="dot"></view>
                <view class="dot"></view>
            </view>
        </scroll-view>
        
        <!-- 输入框和发送按钮 -->
        <view class="input-container">
            <input 
                v-model="question" 
                placeholder="请输入你的问题" 
                class="input" 
                focus
                @confirm="sendQuestion"
                confirm-type="send"
            />
            <button @click="sendQuestion" class="send-button" :disabled="!question.trim()">
                发送
            </button>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { putQuestion } from '../../api/AI/ai';

const question = ref('');
const messages = ref([]);
const scrollTop = ref(0);
const isTyping = ref(false);
const typingSpeed = 30; // 更快的打字速度
let aiMsg="";//存储后端传入的数据

// 加载历史消息
onMounted(() => {
    const savedMessages = uni.getStorageSync('chatMessages');
    if (savedMessages) {
        messages.value = savedMessages;
        scrollToBottom();
    }
});

const sendQuestion = () => {
    if (question.value.trim() === '') return;
    
    // 添加用户消息
    const userMessage = { content: question.value, isUser: true };
    messages.value.push(userMessage);
    saveMessages();
	
	
	//向后端传数据
	 const data = { keyword: question.value }; // 创建对象
	const msg=JSON.stringify(data);
	putQuestion(msg).then(res=>{
		if (res.code == 200) {
			aiMsg=res.data;
			// AI 回答
			simulateAIResponse();
			console.log("传入数据成功");
		}else{
			console.log("接收数据失败！")
		}
	}).catch(err=>{
		console.log("传数据失败",err);
	})
    question.value = '';
    // scrollToBottom();
};
   //AI回答方法
const simulateAIResponse = () => {
    isTyping.value = true;
    scrollToBottom();
    
    // 模拟网络延迟
    setTimeout(() => {
        const aiAnswer =aiMsg.trim();
        const newMessage = { 
            content: aiAnswer, 
            isUser: false, 
            displayContent: '加载中....' 
        };
        messages.value.push(newMessage);
        saveMessages();
        if(aiAnswer.length!=0){
			newMessage.displayContent="";
		}
        let index = 0;
        const timer = setInterval(() => {
            if (index < aiAnswer.length) {
                newMessage.displayContent += aiAnswer[index];
                index++;
                scrollToBottom();
            } else {
                clearInterval(timer);
                isTyping.value = false;
            }
        }, typingSpeed);
    }, 500); // 0.5秒延迟模拟网络请求
};

const scrollToBottom = () => {
    setTimeout(() => {
        scrollTop.value = Math.random() * 1000000; // 随机值确保滚动
    }, 100);
};

const saveMessages = () => {
    uni.setStorageSync('chatMessages', messages.value);
};
</script>
<style scoped>
.container {
    display: flex;
    flex-direction: column;
	padding:0rpx 20rpx;
	margin-top:120rpx;
    height:100vh;
    background-color: #f5f5f5;
}

.message-list {
    flex: 1;
	max-height:95vh;
    padding: 20rpx 20rpx 120rpx; /* 底部留出输入框高度的空间 */
    overflow-y: auto;
    background-color: #f5f5f5;
    box-sizing: border-box; /* 重要：包含padding在高度计算中 */
}

.message-container {
    display: flex;
    flex-direction: column;
    margin-bottom: 20rpx;
}


.message {
    padding: 20rpx;
    border-radius: 12rpx;
    max-width: 80%;
    font-size: 28rpx;
    line-height: 1.5;
    overflow-wrap: break-word;
}

.user-message {
    background-color: #1989fa;
    color: white;
    align-self: flex-end;
    border-bottom-right-radius: 25rpx;
}

.ai-message {
    background-color: white;
    color: #333;
    align-self: flex-start;
    border-bottom-left-radius:25rpx;
    box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.1);
}

.input-container {
    position: fixed;
	height:10%;
    left: 0;
    right: 0;
    bottom: 0;
    padding: 20rpx;
    background-color: white;
    border-top: 1rpx solid #eee;
    align-items: center;
    box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
    z-index: 1000;
	display: flex;
	flex-direction: row;
}

.input {
    width:70%;
    padding: 20rpx;
    border: 1rpx solid #ddd;
    border-radius: 8rpx;
    font-size: 28rpx;
    margin-right: 20rpx;
    background-color: #f9f9f9;
}

.send-button {
    padding: 0 30rpx;
    height: 80rpx;
    line-height: 80rpx;
    background-color: #699CEf;
    color: white;
    border-radius: 8rpx;
    font-size: 28rpx;
	width:30%;
}

.send-button[disabled] {
    background-color: #a0cfff;
}

.typing-indicator {
    display: flex;
    padding: 20rpx;
    align-items: center;
    justify-content: center;
}

.dot {
    width: 12rpx;
    height: 12rpx;
    background-color: #999;
    border-radius: 50%;
    margin: 0 6rpx;
    animation: bounce 1.4s infinite ease-in-out;
}

.dot:nth-child(1) {
    animation-delay: -0.32s;
}

.dot:nth-child(2) {
    animation-delay: -0.16s;
}

@keyframes bounce {
    0%, 80%, 100% { 
        transform: translateY(0);
    }
    40% {
        transform: translateY(-10rpx);
    }
}
</style>